<?php

namespace app\admin\server;

use CURLFile;
use think\Db;
use think\Env;
use think\Exception;

class QyApiWeixinServer
{
    /**
     * 通讯录：获取部门成员详情
     * @param string $access_token
     * @return mixed|string
     * @throws Exception
     */
    public static function getUserList($access_token = '', $department_id = 1)
    {
        if(!$access_token) {
            $access_token = WxworkAccessTokenServer::getWxworkAccessToken();
            if(!$access_token) {
                throw new Exception('access_token 获取失败');
            }
        }
        $url = "https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token=$access_token&department_id=$department_id&fetch_child=1";
        $result = doCurlGetRequest($url);
        if(!($result && $result['errcode'] == 0 && $result['userlist'])) {
            throw new Exception('user_list 获取失败:' . ($result['errmsg'] ?? ''));
        }
        return $result['userlist'];
    }


    /**
     * 批量获取客户详情
     * @param $userIdArr
     * @param $access_token
     * @param $cursor
     * @param $limit
     * @return mixed|string
     * @throws Exception
     */
    public static function getExternalcontactBatchGetByUser($userIdArr, $access_token = '', $cursor = '', $limit = 100)
    {
        $post_data = [
            'userid_list' => $userIdArr,
            'cursor'      => $cursor ?: "",
            'limit'       => $limit ?? 100
        ];
        if(!$access_token) {
            $access_token = WxworkAccessTokenTxlServer::getWxworkAccessToken();
            if(!$access_token) {
                throw new Exception('access_token 获取失败');
            }
        }
        $url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/batch/get_by_user?access_token=$access_token";
        $result = doCurlPostRequest($url, $post_data);

        file_put_contents('./getBatchGetByUser.txt', 'url::' . $url . ';;;;post_data::' . json_encode($post_data) . PHP_EOL, FILE_APPEND);
        file_put_contents('./getBatchGetByUser.txt', 'result::' . json_encode($result) . PHP_EOL, FILE_APPEND);
        if(!($result && $result['errcode'] === 0 && $result['external_contact_list'])) {
//            file_put_contents('./post_data' . date('YmdHis') . '.txt', json_encode($post_data, JSON_UNESCAPED_UNICODE));

            throw new Exception('get_by_user:获取失败' . $result['errmsg'] ?? '');
        }
        return $result;
    }

    /**
     * 部门列表
     * @param $access_token
     * @return mixed|string
     * @throws Exception
     */
    public static function getDepartmentList($access_token = '')
    {
        if(!$access_token) {
            $access_token = WxworkAccessTokenServer::getWxworkAccessToken();
            if(!$access_token) {
                throw new Exception('access_token 获取失败');
            }
        }
        $url = "https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=$access_token";
        $result = doCurlGetRequest($url);
        if(!($result && $result['errcode'] == 0 && isset($result['department']))) {
            throw new Exception(' 部门  获取失败:' . ($result['errmsg'] ?? ''));
        }
        return $result['department'];
    }


    //上传素材
    public static function uploadMedia($cate, $id, $type = 1)
    {
        //cate 1图片 2视频 3文件
        //id tb_local_media表id
        //type 1临时素材 2永久素材

        $access_token = WxworkAccessTokenServer::getWxworkAccessToken();
        if(!$access_token) {
            throw new Exception('access_token 获取失败');
        }

        $chk = Db::name('wxwork_local_media')
            ->where('id', '=', $id)
            ->field('media_path,mediaid,express_time')
            ->find();
        if(empty($chk['mediaid']) || $chk['express_time'] < time()) {
            switch($cate) {
                case 1:
                    $url_up_temp_file = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=$access_token&type=image";
                    break;
                case 2:
                    $url_up_temp_file = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=$access_token&type=video";
                    break;
                case 3:
                    $url_up_temp_file = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=$access_token&type=file";
                    break;
                default:
                    return 'false';
            }
            $path = str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT'] . '/' . $chk['media_path']);
            $path = str_replace('//', '/', $path);
            if(!file_exists($path)) {
                return 'false';
            }
            $upload_result = self::doCurlPostRequestUploadFile($url_up_temp_file, $path);
            if(is_string($upload_result)) {
                return 'false';
            }
            if($upload_result['errcode'] === 0) {
                Db::name('wxwork_local_media')
                    ->where('id', '=', $id)
                    ->update([
                        'mediaid'      => $upload_result['media_id'],
                        'express_time' => get_now_time() + (86400 * 2)
                    ]);
                return $upload_result['media_id'];
            }
            throw new Exception('上传素材  失败:' . ($result['errmsg'] ?? ''));
        }
        return $chk['mediaid'];
    }


    //上传素材解决方案
    public static function doCurlPostRequestUploadFile($url = '', $path = '')
    {
        $curl = curl_init();
        if(class_exists('\CURLFile')) {
            curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);
            $data = array('media' => new CURLFile($path));
        } else {
            curl_setopt($curl, CURLOPT_SAFE_UPLOAD, false);
            $data = array('media' => '@' . $path);
        }
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
        $result = curl_exec($curl);
        if(curl_errno($curl)) {
            return 'Errno' . curl_errno($curl);
        }
        curl_close($curl);
        return json_decode($result, true);
    }

    //获取配置了客户联系功能的成员列表
    public static function getCompanyContactWorker($access_token = '')
    {
        if(!$access_token) {
            $access_token = WxworkAccessTokenServer::getWxworkAccessToken();
            if(!$access_token) {
                throw new Exception('access_token 获取失败');
            }
        }
        $url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_follow_user_list?access_token=$access_token";
        $result = doCurlGetRequest($url);
        if($result && $result['errcode'] === 0 && isset($result['follow_user'])) {
            return $result['follow_user'];
        }
        throw new Exception('获取配置了客户联系功能的成员列表 获取失败');
    }

    //获取标签列表
    public static function getTagList($access_token = '')
    {
        if(!$access_token) {
            $access_token = WxworkAccessTokenServer::getWxworkAccessToken();
            if(!$access_token) {
                throw new Exception('access_token 获取失败');
            }
        }
        $url = 'https://qyapi.weixin.qq.com/cgi-bin/tag/list?access_token=' . $access_token;
        $result = doCurlGetRequest($url);
        if($result && $result['errcode'] === 0 && isset($result['taglist'])) {
            return $result['taglist'];
        }
        throw new Exception(' 获取标签列表  获取失败:' . ($result['errmsg'] ?? ''));
    }

    // 根据 标签ID 获取标签成员
    public static function getTagGet($tagid, $access_token = '')
    {
        if(!$access_token) {
            $access_token = WxworkAccessTokenServer::getWxworkAccessToken();
            if(!$access_token) {
                throw new Exception('access_token 获取失败');
            }
        }
        $url = 'https://qyapi.weixin.qq.com/cgi-bin/tag/get?access_token=' . $access_token . '&tagid=' . $tagid;
        $result = doCurlGetRequest($url);
        if($result && $result['errcode'] === 0) {
            return $result;
        }
        throw new Exception(' 根据 标签ID 获取标签成员 获取失败');
    }

    /**
     * 上传 素材
     * @param int    $cate
     * @param string $media_path
     * @param string $access_token
     * @return mixed|string
     * @throws Exception
     */
    public static function mediaUpload(int $cate, string $media_path, string $access_token = '')
    {
        if(!$access_token) {
            $access_token = WxworkAccessTokenServer::getWxworkAccessToken();
            if(!$access_token) {
                throw new Exception('access_token 获取失败');
            }
        }
        if(!$media_path) {
            return 'false';
        }
        //cate 1图片 2视频 3文件
        $type_list = [
            1 => 'image',
            2 => 'video',
            3 => 'file',
        ];
        /*
          switch($cate) {
              case 1:
                  $url_up_temp_file = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=$access_token&type=image";
                  break;
              case 2:
                  $url_up_temp_file = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=$access_token&type=video";
                  break;
              case 3:
                  $url_up_temp_file = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=$access_token&type=file";
                  break;
              default:
                  return 'false';
          }*/
        $type_list_arr = array_keys($type_list);
        if(!in_array($cate, $type_list_arr)) {
            return 'false';
        }
        $type = $type_list[$cate];
        $url_up_temp_file = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=$access_token&type=" . $type;

        $path = str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT'] . '/' . $media_path);
        $path = str_replace('//', '/', $path);
        if(!file_exists($path)) {
            return 'false';
        }
        $upload_result = self::doCurlPostRequestUploadFile($url_up_temp_file, $path);
        if(is_string($upload_result)) {
            throw new Exception('上传 素材 获取失败');
        }
        if(!($upload_result && $upload_result['errcode'] === 0 && isset($upload_result['media_id']))) {
            throw new Exception('上传 素材 获取失败');
        }
        return $upload_result['media_id'];
    }

    /**
     * 上传附件资源
     * @param string $media_type
     * @param int    $attachment_type
     * @param string $media_path
     * @param string $access_token
     * @return mixed|string
     * @throws Exception
     */
    public static function mediaUploadAttachment(string $media_type, int $attachment_type, string $media_path, string $access_token = '')
    {
        //$media_type  图片image  视频video  文件file
        //$attachment_type 1：朋友圈；2:商品图册
        //$id tb_local_media表id

        if(!$access_token) {
            $access_token = WxworkAccessTokenServer::getWxworkAccessToken();
            if(!$access_token) {
                throw new Exception('access_token 获取失败');
            }
        }
        if(!in_array($media_type, ['image', 'video', 'file']) || !in_array($attachment_type, [1, 2]) || !$media_path) {
            return 'false';
        }
        $url_up_temp_file = "https://qyapi.weixin.qq.com/cgi-bin/media/upload_attachment?access_token=$access_token&media_type=$media_type&attachment_type=$attachment_type";
        $path = str_replace('\\', '/', Env::get('root_path') . 'public' . $media_path);
        $upload_result = self::doCurlPostRequestUploadFile($url_up_temp_file, $path);
        if(!($upload_result && $upload_result['errcode'] === 0 && isset($upload_result['media_id']))) {
            throw new Exception('上传附件资源 获取失败');
        }
        return $upload_result['media_id'];
    }

    /**
     *获取客户朋友圈全部的发表记录
     * @param $time_area
     * @param $cursor
     * @param $access_token
     * @return mixed|string
     * @throws Exception
     */
    public static function getExternalcontactGetMomentList($time_area = '', $cursor = '', $access_token = '')
    {
        //不带时间区间访问时自动同步最近30天的数据
        if(!$access_token) {
            $access_token = WxworkAccessTokenServer::getWxworkAccessToken();
            if(!$access_token) {
                throw new Exception('access_token 获取失败');
            }
        }
        $url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_moment_list?access_token=$access_token";
        if(empty($time_area)) {
            $time_area = time_to_date((get_now_time() - (86400 * 29)), 'Y-m-d') . ' - ' . get_now_date('Y-m-d');
        }
        $timeArr1 = explode(" - ", $time_area);
        $timeArrStart1 = date_to_time($timeArr1[0]);
        $timeArrEnd1 = date_to_time($timeArr1[1] . ' 23:59:59');
        //limit最大 20
        $post_data = [
            'start_time' => $timeArrStart1,
            'end_time'   => $timeArrEnd1,
            'cursor'     => $cursor,
            'limit'      => 20
        ];
        $result = doCurlPostRequest($url, $post_data);
        if($result && $result['errcode'] === 0 && isset($result['moment_list'])) {
            return $result['moment_list'];
        }
        throw new Exception('客户朋友圈全部的发表记录 获取失败');
    }

    /**
     * 获取部门成员详情列表
     * @param $access_token
     * @param $department_id
     * @param $fetch_child
     * @return void
     */
    public static function departmentUserList($access_token = '', int $department_id = 1, int $fetch_child = 1)
    {
        if(!$access_token) {
            $access_token = WxworkAccessTokenServer::getWxworkAccessToken();
            if(!$access_token) {
                throw new Exception('access_token 获取失败');
            }
        }
        $url = "https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token=$access_token&department_id=$department_id&fetch_child=$fetch_child";
        $result = doCurlGetRequest($url);
        if($result && $result['errcode'] === 0 && isset($result['userlist'])) {
            return $result['userlist'];
        }
        throw new Exception('部门成员详情  获取失败');
    }
}